package com.mmall.service.iml;

import com.mmall.common.Const;
import com.mmall.common.ServerResponse;
import com.mmall.common.TokenCache;
import com.mmall.dao.UserMapper;
import com.mmall.pojo.User;
import com.mmall.service.IUserService;
import com.mmall.util.MD5Util;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.UUID;

/**
 * Created by maomao
 */

@Service("iUserService")
public class UserServiceImpl implements IUserService {


    @Autowired
    private UserMapper userMapper;

    @Override
    public ServerResponse<User> login(String username, String password) {

        int resultCount =userMapper.checkUsername(username);

        if(resultCount ==0){

            return ServerResponse.createByErrorMessage("用户不存在");

        }

            //todo 密码登录MD5

            String md5password = MD5Util.MD5EncodeUtf8(password);  // 这个很重要哦！！！！

            User user = userMapper.selectLogin(username,md5password);

            if(user==null){

                return ServerResponse.createByErrorMessage("用户不存在或者密码不正确");
            }

            user.setPassword(StringUtils.EMPTY);

            return ServerResponse.createBySuccess("恭喜您登录成功",user);

    }

    /*public ServerResponse<String> register(User user){

        int resultCount = userMapper.checkUsername(user.getUsername());

        if(resultCount>0){

            return ServerResponse.createByErrorMessage("用户名存在");

        }

        resultCount = userMapper.checkEmail(user.getEmail());

        if(resultCount>0){
            return ServerResponse.createByErrorMessage("您输入的Email已经存在");
        }


        //
        user.setRole(Const.Role.ROLE_CUSTOMER);

        // MD5 加密

        user.setUsername(MD5Util.MD5EncodeUtf8(user.getPassword()));


        resultCount = userMapper.insert(user);

        if(resultCount==0){

            return ServerResponse.createByErrorMessage("注册失败");
        }

        return ServerResponse.createBySuccessMessage("注册成功");


    }*/


    public ServerResponse<String> register(User user){

        // 调用checkValid方法

        ServerResponse validResponse = this.checkValid(user.getUsername(),user.getEmail());

        if(!validResponse.isSuccess()){
            return validResponse;
        }

        validResponse = this.checkValid(user.getEmail(),Const.EMAIL);

        if (!validResponse.isSuccess()){
            return validResponse;

        }
        user.setRole(Const.Role.ROLE_CUSTOMER);

        user.setPassword(MD5Util.MD5EncodeUtf8(user.getPassword()));

        int resultCount = userMapper.insert(user);

        if(resultCount==0){

            return ServerResponse.createByErrorMessage("注册失败");
        }

        return ServerResponse.createBySuccessMessage("恭喜您注册成功");
    }

        public ServerResponse<String> checkValid(String str,String type){


            if(StringUtils.isNotBlank(type)){

               // start to verify
                // check username
                if(Const.USERNAME.equals(type)){

                    int resultCount = userMapper.checkUsername(str);

                    if(resultCount>0){

                        return ServerResponse.createByErrorMessage("该用户已经存在");
                    }
                }

                // check email

                if(Const.EMAIL.equals(type)){

                    int resultCount = userMapper.checkEmail(str);

                    if(resultCount>0){

                    return ServerResponse.createByErrorMessage("您输入的Emain已经存在");
                    }
                }
            }else {

                return ServerResponse.createByErrorMessage("参数错误！！！！");
            }

            return ServerResponse.createBySuccessMessage("校验成功");

        }

        public ServerResponse selectQuestion(String username){

            ServerResponse validResponse = this.checkValid(username,Const.USERNAME);
            if(validResponse.isSuccess()){


                return ServerResponse.createByErrorMessage("用记不存在");
            }

            String question = userMapper.selectQuestionByUsername(username);

            if(StringUtils.isNotBlank(question)){

                return ServerResponse.createBySuccess(question);

            }

            return ServerResponse.createByErrorMessage("找回密码的问题是空的！！");

        }

        public ServerResponse<String> checkAnswer(String username,String question,String answer){

        int resultCount = userMapper.checkAnswer(username,question,answer);

            if(resultCount>0){

                //  is and right

                String forgetToken = UUID.randomUUID().toString();

                TokenCache.setKey(TokenCache.TOKEN_PREFIX+username,forgetToken);

                return ServerResponse.createBySuccess(forgetToken);


            }

            return ServerResponse.createByErrorMessage("问题的答案不对");

        }

        public ServerResponse<String> forgetResetPassword(String username,String passwordnew,String forgetToken){

            if(StringUtils.isBlank(forgetToken)){

                return ServerResponse.createByErrorMessage("参数不正确，token需要传递");
            }

            ServerResponse validResponse = this.checkValid(username,Const.USERNAME);

            if(validResponse.isSuccess()){

                //

                return ServerResponse.createByErrorMessage("用户不存在");

            }

            String token = TokenCache.getKey(TokenCache.TOKEN_PREFIX+username);

            // 校验 token

            if(StringUtils.isBlank(token)){

                return ServerResponse.createByErrorMessage("token 无效或者过期");
            }

            if (StringUtils.equals(forgetToken,token)) {

                String md5password = MD5Util.MD5EncodeUtf8(passwordnew);

                int  rowCount = userMapper.updatePasswordByUsername(username,md5password);

                if(rowCount>0){

                    return ServerResponse.createBySuccessMessage("修改密码成功");

                }
            }else {

                return ServerResponse.createByErrorMessage("token错误，请重新获取重置密码的token");

            }

            return ServerResponse.createByErrorMessage("修改密码失败！！！" );

        }

        public ServerResponse<String> resetPassword(String passwordnew, String passwordold,User user){
                // 防止横向越权，要校验一下这个用户的旧密码，一定要指定是这个用户，因为我们
                    // 会查询一个count(1),如果不指定id,查询结果就是true cout>0

            int resultCount  = userMapper.checkPassword(MD5Util.MD5EncodeUtf8(passwordold),user.getId());

            if(resultCount == 0){

                return ServerResponse.createByErrorMessage("旧密码错误！！！");
            }

            user.setPassword(MD5Util.MD5EncodeUtf8(passwordnew));

            int updateCount = userMapper.updateByPrimaryKeySelective(user);

            if(updateCount>0){
                return ServerResponse.createBySuccessMessage("密码更新成功");
            }

            return ServerResponse.createByErrorMessage("密码更新失败！！！");

        }


        public ServerResponse<User> updateInformation(User user){
        // username 是不能被更新
            // email 也要进行一个校验，校验新的email是不是已经存在
            // 并且存在的email如果相同的话，不能是我们当前的这个用户

            int resultCount  = userMapper.checkEmailByUserId(user.getEmail(),user.getId());

            if(resultCount > 0){

                return ServerResponse.createByErrorMessage("Email 已经存在 ,请更换Email");
            }

            User updateuser = new User();

            updateuser.setId(user.getId());
            updateuser.setEmail(user.getEmail());
            updateuser.setPhone(user.getPhone());
            updateuser.setQuestion(user.getQuestion());
            updateuser.setAnswer(user.getAnswer());

            int updateCount = userMapper.updateByPrimaryKeySelective(updateuser);

            if(updateCount>0){

                return ServerResponse.createBySuccess("更新个人信息成功",updateuser);
            }

            return ServerResponse.createByErrorMessage("更新个人信息失败");

        }

        public ServerResponse<User> getInformation(Integer userId){
            User user = userMapper.selectByPrimaryKey(userId);

            if(user==null){

                return ServerResponse.createByErrorMessage("找不到当前用户");
            }

            user.setPassword(StringUtils.EMPTY);

            return ServerResponse.createBySuccess(user);

        }


}
